package com.taoes.simpledocker.config;

import com.taoes.simpledocker.config.model.SwaggerProperties;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;

import static springfox.documentation.builders.RequestHandlerSelectors.withMethodAnnotation;

/**
 * @BelongsProject: SimpleDocker
 * @BelongsPackage: com.taoes.simpledocker.config
 * @Author: lfsong
 * @CreateTime: 2022-11-09  14:50
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {

    @Bean(value = "dockerBean")
    public Docket dockerBean(SwaggerProperties swaggerProperties) {

        ParameterBuilder clientIdPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        clientIdPar.name("clientId").description("管理docker终端的Id,默认为本地docker")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build(); //header中的ticket参数非必填，传空也可以
        pars.add(clientIdPar.build());  //根据每个方法名也知道当前方法在设置什么参数

        //指定使用Swagger2规范
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(swaggerProperties))
                //分组名称
                .groupName("用户服务")
                .select()
                // 添加过滤条件，谓词过滤predicate，这里是自定义注解进行过滤
                .apis(withMethodAnnotation(ApiOperation.class))
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.taoes.simpledocker.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars);
        return docket;
    }

    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        SwaggerProperties.Contact contact = swaggerProperties.getContact();
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .contact(new Contact(contact.getName(), contact.getUrl(), contact.getEmail()))
                .version(swaggerProperties.getVersion())
                .build();
    }
}

